<template>
  <div class="create-wrap">
    <el-card>
      <div class="header-row">
        <div class="title">编辑工艺路线</div>
        <div class="spacer"></div>
      </div>
    </el-card>

    <el-card class="section-card">
      <template #header>
        <div class="section-title">基础信息</div>
      </template>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="base-form">
        <div class="grid">
          <div class="col">
            <el-form-item label="工艺路线编号" prop="processRouteNumber">
              <div class="inline">
                <el-input v-model="form.processRouteNumber" placeholder="请输入" />
                <div class="gap-12"></div>
                <el-switch v-model="form.autoCode" @change="handleAuto" />
                <div class="gap-6"></div>
                <span class="muted">系统编号</span>
              </div>
            </el-form-item>
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio :label="true">启用</el-radio>
                <el-radio :label="false">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div class="col">
            <el-form-item label="工艺路线名称" prop="processRouteName">
              <el-input v-model="form.processRouteName" placeholder="请输入" />
            </el-form-item>
          </div>
        </div>
        <el-form-item label="说明">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remarks" type="textarea" :rows="3" placeholder="请输入" />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="section-card">
      <template #header>
        <div class="section-title">工序组成</div>
      </template>
      <div class="op-row">
        <el-button type="primary" @click="openAddProcess">新增</el-button>
      </div>
      <el-table :data="processList" height="220">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="processNumber" label="工序编号" min-width="200" />
        <el-table-column prop="processName" label="工序" min-width="140" />
        <el-table-column prop="nextProcess" label="下一道工序" min-width="140" />
        <el-table-column prop="relationship" label="关系" min-width="100" />
        <el-table-column prop="isCriticalProcess" label="关键工序" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isCriticalProcess ? 'danger' : 'info'">{{ scope.row.isCriticalProcess ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="preparationTime" label="准备时间" width="120" />
        <el-table-column prop="waitingTime" label="等待时间" width="120" />
        <el-table-column prop="remarks" label="备注" min-width="160" />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-link type="danger" underline="never" @click="removeProcess(scope.row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="section-card">
      <template #header>
        <div class="section-title">关联产品</div>
      </template>
      <div class="op-row">
        <el-button type="primary" @click="openSelectProduct">添加</el-button>
      </div>
      <el-table :data="relatedProductsView" height="220">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="productNumber" label="产品编号" min-width="140" />
        <el-table-column prop="productName" label="产品名称" min-width="140" />
        <el-table-column prop="specificationModel" label="规格型号" min-width="140" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="productType" label="产品类型" min-width="120" />
        <el-table-column prop="productAttribute" label="产品属性" min-width="120" />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-link type="danger" underline="never" @click="removeRelatedProduct(scope.row)">移除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="section-card">
      <div class="op-bottom">
        <el-button size="large" @click="handleCancel">返回</el-button>
        <el-button size="large" type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-card>

    <!-- 工序新增弹窗 -->
    <el-dialog v-model="processDialogVisible" title="新增工序" width="560px">
    <el-form :model="procForm" label-width="100px">
      <el-form-item label="工序编号">
        <el-input v-model="procForm.processNumber" disabled />
      </el-form-item>
      <el-form-item label="序号">
        <el-input-number v-model="procForm.serialNumber" :min="1" />
      </el-form-item>
      <el-form-item label="工序">
        <el-input v-model="procForm.processName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="下一道工序">
        <el-input v-model="procForm.nextProcess" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="关系">
        <el-input v-model="procForm.relationship" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="关键工序">
        <el-switch v-model="procForm.isCriticalProcess" />
      </el-form-item>
      <el-form-item label="准备时间">
        <el-input-number v-model="procForm.preparationTime" :min="0" />
      </el-form-item>
      <el-form-item label="等待时间">
        <el-input-number v-model="procForm.waitingTime" :min="0" />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="procForm.remarks" type="textarea" :rows="2" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="processDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmAddProcess">确定</el-button>
      </span>
    </template>
    </el-dialog>

    <!-- 产品选择弹窗 -->
    <el-dialog v-model="productDialogVisible" title="选择产品" width="800px">
      <el-table :data="productList" height="400" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="productNumber" label="产品编号" min-width="140" />
        <el-table-column prop="productName" label="产品名称" min-width="140" />
        <el-table-column prop="specificationModel" label="规格型号" min-width="140" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="productType" label="产品类型" min-width="120" />
        <el-table-column prop="productAttribute" label="产品属性" min-width="120" />
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="productDialogVisible=false">取消</el-button>
          <el-button type="primary" @click="confirmSelectProduct">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { WriteClients, ReadClients } from '@/Urls/AxiosHelper'

const router = useRouter()
const route = useRoute()

const writeClient = WriteClients[3]
const readClient = ReadClients[3]

const props = defineProps<{ id?: number | string, originPage?: 'list' | 'detail' }>()
const id = computed(() => props.id || route.query.id)
const originPage = computed(() => props.originPage || route.query.origin || 'list')

// 后端文档接口路径
const API_UPDATE_ROUTE = '/productwrite/api/ProcessRoute/UpdateProcessRoute'
const API_GET_ROUTE = '/productread/api/ProcessRoute/GetProcessRouteById'
const API_GET_PROCESS = '/productread/api/Process/GetProcessByProcessRouteNumber'
const API_GET_PRODUCT_PROCESS = '/productread/api/ProductProcess/ProductProcessShow'

const formRef = ref()
const loading = ref(false)
const form = reactive({
  processRouteNumber: '',
  autoCode: false,
  processRouteName: '',
  status: true,
  description: '',
  remarks: '',
})

const rules = {
  processRouteNumber: [{ required: true, message: '请输入工艺路线编号', trigger: 'blur' }],
  processRouteName: [{ required: true, message: '请输入工艺路线名称', trigger: 'blur' }],
}

function generateGuid(){
  const buf = new Uint8Array(16)
  crypto.getRandomValues(buf)
  const s = [...buf].map(b=>b.toString(16).padStart(2,'0'))
  s[6] = (parseInt(s[6],16) & 0x0f | 0x40).toString(16)
  s[8] = (parseInt(s[8],16) & 0x3f | 0x80).toString(16)
  return `${s[0]}${s[1]}${s[2]}${s[3]}-${s[4]}${s[5]}-${s[6]}${s[7]}-${s[8]}${s[9]}-${s[10]}${s[11]}${s[12]}${s[13]}${s[14]}${s[15]}`
}

function handleAuto(){
  if(form.autoCode){
    form.processRouteNumber = generateGuid()
    // 清除验证状态
    formRef.value?.clearValidate('processRouteNumber')
  }else{
    form.processRouteNumber = ''
  }
}

// 获取工艺路线详情
async function fetchRouteDetail(){
  try{
    loading.value = true
    console.log('获取工艺路线详情，ID:', id.value)
    const res = await readClient.get(API_GET_ROUTE, { params: { Id: id.value } })
    console.log('工艺路线详情响应:', res)
    const data = res?.data?.data || res?.data || res
    if(data){
      Object.assign(form, {
        processRouteNumber: data.processRouteNumber || '',
        processRouteName: data.processRouteName || '',
        status: data.status !== false,
        description: data.description || '',
        remarks: data.remarks || '',
        autoCode: false
      })
      console.log('工艺路线详情设置完成:', form)
    }
  }catch(err){
    console.error('获取工艺路线详情失败:', err)
    ElMessage.error('获取工艺路线详情失败')
  }finally{
    loading.value = false
  }
}

// 获取工序列表
async function fetchProcessList(){
  try{
    console.log('获取工序列表，processRouteNumber:', form.processRouteNumber)
    // 根据图片，接口是 /api/Process/GetProcessById，参数是 processRouteNumber
    const res = await readClient.get('/productread/api/Process/GetProcessById', { params: { processRouteNumber: form.processRouteNumber } })
    console.log('工序列表响应:', res)
    const data = res?.data?.data || res?.data || res
    if(Array.isArray(data)){
      processList.value = data.map((item: any) => ({
        processNumber: item.processNumber || '',
        serialNumber: item.serialNumber || 1,
        processName: item.processName || '',
        nextProcess: item.nextProcess || '',
        relationship: item.relationship || '',
        isCriticalProcess: item.isCriticalProcess || false,
        preparationTime: item.preparationTime || 0,
        waitingTime: item.waitingTime || 0,
        remarks: item.remarks || '',
        isDelete: false
      }))
      console.log('工序列表处理结果:', processList.value)
    }
  }catch(err){
    console.error('获取工序列表失败:', err)
    ElMessage.error('获取工序列表失败')
  }
}

// 获取关联产品列表
async function fetchRelatedProducts(){
  try{
    const res = await readClient.get(API_GET_PRODUCT_PROCESS, { params: { processRouteNumber: form.processRouteNumber } })
    const data = res?.data?.data || res?.data || res
    if(Array.isArray(data)){
      relatedProductsView.value = data.map((item: any) => ({
        productNumber: item.productNumber || '',
        productName: item.productName || '',
        specificationModel: item.specificationModel || '',
        unit: item.unit || '',
        productType: item.productType || '',
        productAttribute: item.productAttribute || ''
      }))
      relatedProductNumbers.value = data.map((item: any) => item.productNumber).filter(Boolean)
    }
  }catch(err){
    console.error('获取关联产品列表失败:', err)
    ElMessage.error('获取关联产品列表失败')
  }
}

async function handleSave(){
  // @ts-ignore
  formRef.value?.validate(async (ok:boolean)=>{
    if(!ok) return
    try{
      const payload = {
        Id: props.id,
        processRouteNumber: form.processRouteNumber,
        processRouteName: form.processRouteName,
        status: form.status,
        description: form.description,
        remarks: form.remarks,
      }
      const res = await writeClient.post(API_UPDATE_ROUTE, payload)
      if(res && (res.status===200 || res?.data?.code===200 || res?.data?.success)){
        ElMessage.success('保存成功')
        const targetRoute = originPage.value === 'detail' ? 'ProcessRouteDetail' : 'ProcessRouteInfo'
        router.push({ name: targetRoute, query: originPage.value === 'detail' ? { id: id.value } : {} })
      }else{ throw new Error(res?.data?.message || '保存失败') }
    }catch(err:any){
      console.error('保存失败:', err)
      ElMessage.error(err?.response?.data?.message || err?.message || '保存失败')
    }
  })
}

function handleCancel(){
  const targetRoute = originPage.value === 'detail' ? 'ProcessRouteDetail' : 'ProcessRouteInfo'
  router.push({ name: targetRoute, query: originPage.value === 'detail' ? { id: id.value } : {} })
}

// -------------------- 前端：工序组成（完整工序数组） --------------------
type ProcItem = {
  processNumber: string
  serialNumber: number
  processName: string
  nextProcess?: string
  relationship?: string
  isCriticalProcess?: boolean
  preparationTime?: number
  waitingTime?: number
  remarks?: string
  isDelete?: boolean
}

const processList = ref<ProcItem[]>([])
const processDialogVisible = ref(false)
const procForm = reactive<ProcItem>({
  processNumber: '',
  serialNumber: 1,
  processName: '',
  nextProcess: '',
  relationship: '',
  isCriticalProcess: false,
  preparationTime: 0,
  waitingTime: 0,
  remarks: '',
})

function openAddProcess(){
  Object.assign(procForm, { processNumber: generateGuid(), serialNumber: (processList.value.length||0)+1, processName:'', nextProcess:'', relationship:'', isCriticalProcess:false, preparationTime:0, waitingTime:0, remarks:'', isDelete:false })
  processDialogVisible.value = true
}
function confirmAddProcess(){
  if(!procForm.processName){ ElMessage.error('请输入工序'); return }
  processList.value.push({ ...procForm })
  console.log('添加工序后，processList:', processList.value)
  processDialogVisible.value = false
}
function removeProcess(row: ProcItem){
  processList.value = processList.value.filter(it=>it.processNumber!==row.processNumber)
}

// -------------------- 前端：关联产品（仅缓存产品编号数组；另存展示列表） --------------------
type ProductItem = {
  productNumber: string
  productName: string
  specificationModel?: string
  unit?: string
  productType?: string
  productAttribute?: string
}

const relatedProductNumbers = ref<string[]>([])
const relatedProductsView = ref<ProductItem[]>([])

const productDialogVisible = ref(false)
const productList = ref<ProductItem[]>([])
const selectedProducts = ref<ProductItem[]>([])

function openSelectProduct(){
  fetchProducts()
  productDialogVisible.value = true
}
async function fetchProducts(){
  try{
    const res = await readClient.get('/productread/api/Product/ProductShow', {
      params: {
        pageIndex: 1,
        pageSize: 1000, // 获取所有产品
      }
    })
    const payload = res?.data ?? {}
    const data = payload.data ?? payload
    const items = data.data ?? data.items ?? data.rows ?? data.list ?? []
    
    if(Array.isArray(items)){
      productList.value = items.map((item: any) => ({
        productNumber: item.productNumber || '',
        productName: item.productName || '',
        specificationModel: item.specificationModel || '',
        unit: item.unit || '',
        productType: item.productType || '',
        productAttribute: item.productAttribute || ''
      }))
    }
  }catch(err){
    console.error('获取产品列表失败:', err)
    ElMessage.error('获取产品列表失败')
  }
}
function handleSelectionChange(selection: ProductItem[]){
  selectedProducts.value = selection
}
function confirmSelectProduct(){
  selectedProducts.value.forEach(product => {
    if(!relatedProductNumbers.value.includes(product.productNumber)){
      relatedProductNumbers.value.push(product.productNumber)
      relatedProductsView.value.push(product)
    }
  })
  productDialogVisible.value = false
}
function removeRelatedProduct(row:{ productNumber:string }){
  relatedProductNumbers.value = relatedProductNumbers.value.filter(x=>x!==row.productNumber)
  relatedProductsView.value = relatedProductsView.value.filter(x=>x.productNumber!==row.productNumber)
}

// 初始化数据
onMounted(async () => {
  await fetchRouteDetail()
  if(form.processRouteNumber){
    await fetchProcessList()
    await fetchRelatedProducts()
  }
})
</script>

<style scoped>
.create-wrap{ display:flex; flex-direction:column; gap:12px; }
.header-row{ display:flex; align-items:center; }
.title{ font-size:20px; font-weight:700; }
.spacer{ flex:1; }
.section-card{ background:#fff; border-radius:8px; }
.section-title{ text-align:center; color:#606266; }
.base-form{ margin-top:8px; }
.grid{ display:grid; grid-template-columns: 1fr 1fr; column-gap:24px; }
.col{ display:flex; flex-direction:column; gap:12px; }
.inline{ display:flex; align-items:center; }
.gap-12{ width:12px; }
.gap-6{ width:6px; }
.muted{ color:#909399; font-size:14px; }
.op-row{ margin-bottom:12px; }
.op-bottom{ display:flex; justify-content:center; gap:16px; }
.dialog-footer{ display:flex; justify-content:flex-end; gap:8px; }
</style>
